import { onMounted, onUnmounted, watch, Ref, ref } from "vue"
import { useRoute, useRouter } from "vue-router"
import { saveSurvey } from "@/db/localDb"

export function useAutoSave(id: string, data: Record<string, any>, enabled: Ref<boolean>, meta: { title: Ref<string>; totalTime: Ref<number> }) {
  let interval: number | undefined
  const router = useRouter()
  const route = useRoute()
  const hasPushedId = ref(false) // 避免重复 replace

  watch(enabled, (val) => {
    if (val) {
      interval = setInterval(() => {
        console.log("开启自动保存", meta.totalTime.value)
        saveSurvey({
          id,
          workingTime: meta.totalTime.value,
          respondent: data.metadata.respondent.answer,
          investigators: data.metadata.investigator.answer,
          investigationDate: data.metadata.surveyDate.answer,
          quesNumber:
            data.fields.monitoringPointNumber.answer +
            "-" +
            data.fields.townNumber.answer +
            "-" +
            data.fields.villageNumber.answer +
            "-" +
            data.fields.familyNumber.answer,
          areaCode: data.fields.monitoringPointNumber.answer + "-" + data.fields.townNumber.answer + "-" + data.fields.villageNumber.answer,
          title: meta.title.value || `-`,
          quesData: JSON.parse(JSON.stringify(data)),
          updatedAt: Date.now()
        })
        // console.log("自动保存数据", data)
        // ✅ 第一次保存成功后把 id 加入到 URL 中（如果原来 URL 没有 id）
        if (!hasPushedId.value && !route.query.id) {
          hasPushedId.value = true
          router.replace({
            query: {
              ...route.query,
              id
            }
          })
        }
      }, 10000)
    }
  })

  onUnmounted(() => {
    if (interval) clearInterval(interval)
  })
}
